<template>
  <div class="embedded-chat-container">
    <div class="chat-header">
      <div class="flex items-center justify-between">
        <div class="flex items-center space-x-3">
          <div class="w-10 h-10 bg-primary-600 rounded-full flex items-center justify-center">
            <svg class="w-6 h-6 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
            </svg>
          </div>
          <div>
            <h3 class="text-lg font-semibold text-gray-900">AI Art Assistant</h3>
            <p class="text-sm text-gray-600">Get creative guidance and tips</p>
          </div>
        </div>
        
        <!-- 会话管理按钮 -->
        <div class="flex items-center space-x-2">
          <!-- 新建聊天按钮 -->
          <button
            @click="createNewChat"
            class="p-2 text-gray-600 hover:text-primary-600 hover:bg-primary-50 rounded-lg transition-colors duration-200"
            title="New Chat"
          >
            <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
            </svg>
          </button>
          
          <!-- 会话列表按钮 -->
          <div class="relative">
            <button
              @click="toggleSessionList"
              class="p-2 text-gray-600 hover:text-primary-600 hover:bg-primary-50 rounded-lg transition-colors duration-200"
              title="Chat History"
            >
              <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7V3m8 4V3m-9 8h10M5 21h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
              </svg>
            </button>
            
            <!-- 会话列表下拉菜单 -->
            <Transition
              enter-active-class="transition-all duration-200 ease-out"
              enter-from-class="opacity-0 scale-95"
              enter-to-class="opacity-100 scale-100"
              leave-active-class="transition-all duration-150 ease-in"
              leave-from-class="opacity-100 scale-100"
              leave-to-class="opacity-0 scale-95"
            >
              <div
                v-if="showSessionList"
                class="absolute right-0 top-full mt-2 w-64 bg-white rounded-lg shadow-lg border border-gray-200 z-50 max-h-80 overflow-y-auto"
              >
                <div class="p-3 border-b border-gray-100">
                  <h4 class="text-sm font-medium text-gray-900">Chat Sessions</h4>
                </div>
                <div class="py-2">
                  <div
                    v-for="session in sessions"
                    :key="session.id"
                    @click="switchToSession(session.id)"
                    class="flex items-center justify-between px-3 py-2 hover:bg-gray-50 cursor-pointer group"
                    :class="{ 'bg-primary-50': currentSessionId === session.id }"
                  >
                    <div class="flex-1 min-w-0">
                      <div class="text-sm font-medium text-gray-900 truncate">
                        {{ session.title }}
                      </div>
                      <div class="text-xs text-gray-500">
                        {{ formatDate(session.updatedAt) }}
                      </div>
                    </div>
                    <button
                      @click.stop="deleteSession(session.id)"
                      class="opacity-0 group-hover:opacity-100 p-1 text-gray-400 hover:text-red-600 transition-all duration-200"
                      title="Delete Session"
                    >
                      <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                      </svg>
                    </button>
                  </div>
                </div>
              </div>
            </Transition>
          </div>
        </div>
      </div>
    </div>

    <div class="chat-messages" ref="messagesContainer">
      <!-- 空状态显示 -->
      <div v-if="messages.length === 0" class="empty-state">
        <div class="empty-state-content">
          <div class="empty-state-icon">
            <svg class="w-16 h-16 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z" />
            </svg>
          </div>
          <h3 class="empty-state-title">Welcome to AI Art Assistant</h3>
          <p class="empty-state-description">Start a conversation to get creative guidance and tips for your AI-generated artwork.</p>
          <div class="empty-state-actions">
            <button
              @click="sendQuickMessage('Create a photorealistic portrait of a person')"
              class="empty-state-button"
            >
              Try Example Prompt
            </button>
          </div>
        </div>
      </div>
      
      <!-- 消息列表 -->
      <div v-for="message in messages" :key="message.id" class="message-item" :class="message.role === 'user' ? 'justify-end' : 'justify-start'">
        <!-- AI消息 -->
        <div v-if="message.role === 'assistant'" class="flex items-start space-x-3">
          <!-- AI头像 - 完全独立的元素，与气泡分离 -->
          <div class="w-8 h-8 bg-primary-100 rounded-full flex items-center justify-center flex-shrink-0 mt-1 shadow-sm">
            <svg class="w-4 h-4 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
            </svg>
          </div>
          
          <!-- AI消息气泡 - 完全独立的元素，与头像分离 -->
          <div class="bg-white border border-gray-200 rounded-xl shadow-md hover:shadow-lg transition-all duration-300 px-4 py-3 max-w-xs sm:max-w-sm md:max-w-md lg:max-w-lg xl:max-w-xl break-words overflow-wrap-anywhere">
            <div class="text-sm text-gray-600 mb-1 font-medium">AI Art Assistant</div>
            <div class="ai-message-content">
              <div v-if="message.content" class="message-content-formatted" v-html="formatMessage(message.content)"></div>
              <div v-else-if="isMessageStreaming(message.id)" class="thinking-indicator">
                <div class="thinking-dots">
                  <div class="dot"></div>
                  <div class="dot"></div>
                  <div class="dot"></div>
                </div>
                <span class="thinking-text">AI is thinking...</span>
              </div>
              <div v-if="message.content && isMessageStreaming(message.id)" class="streaming-cursor">|</div>
              <!-- 消息状态和时间戳 -->
              <div class="message-meta">
                <div class="message-timestamp">{{ formatTime(message.timestamp) }}</div>
                <div v-if="isMessageStreaming(message.id)" class="message-status">
                  <div class="status-dot"></div>
                  <span class="status-text">Streaming</span>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <!-- 用户消息 -->
        <div v-else class="flex items-start space-x-3">
          <!-- 用户消息气泡 - 完全独立的元素，与头像分离 -->
          <div class="bg-primary-600 text-white border border-primary-500 rounded-xl shadow-md hover:shadow-lg transition-all duration-300 px-4 py-3 max-w-xs sm:max-w-sm md:max-w-md lg:max-w-lg xl:max-w-xl break-words overflow-wrap-anywhere">
            <div class="user-message-content">
              {{ message.content }}
              <!-- 用户消息时间戳 -->
              <div class="user-message-meta">
                <div class="user-message-timestamp">{{ formatTime(message.timestamp) }}</div>
              </div>
            </div>
          </div>
          
          <!-- 用户头像 - 完全独立的元素，与气泡分离 -->
          <div class="w-8 h-8 bg-primary-100 rounded-full flex items-center justify-center flex-shrink-0 mt-1 shadow-sm">
            <svg class="w-4 h-4 text-primary-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
            </svg>
          </div>
        </div>
      </div>
      
    </div>

    <div class="chat-input-container">
      <form @submit.prevent="sendMessage" class="flex space-x-3">
        <div class="flex-1 relative">
          <input
            v-model="inputMessage"
            type="text"
            placeholder="Ask about AI art techniques, prompts, or get creative inspiration..."
            class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:ring-2 focus:ring-primary-500 focus:border-transparent resize-none"
            :disabled="isLoading"
          />
        </div>
         <button
           v-if="!isLoading"
           type="submit"
           :disabled="!inputMessage.trim()"
           class="px-6 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200"
         >
           <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
             <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 19l9 2-9-18-9 18 9-2zm0 0v-8" />
           </svg>
         </button>
         <button
           v-else
           type="button"
           @click="stopStreaming"
           class="px-6 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700 transition-colors duration-200"
           title="Stop AI response"
         >
           <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
             <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 6h12v12H6z" />
           </svg>
         </button>
      </form>
    </div>
  </div>
  
  <!-- 图片模态框 -->
  <div 
    v-if="showImageModal" 
    class="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50"
    @click="closeImageModal"
  >
    <div class="relative max-w-4xl max-h-[90vh] bg-white rounded-lg overflow-hidden shadow-2xl">
      <!-- 关闭按钮 -->
      <button
        @click="closeImageModal"
        class="absolute top-4 right-4 z-10 bg-black bg-opacity-50 text-white rounded-full p-2 hover:bg-opacity-70 transition-all duration-200"
      >
        <svg class="w-6 h-6" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
        </svg>
      </button>
      
      <!-- 图片 -->
      <img 
        :src="modalImageUrl" 
        alt="Generated Image" 
        class="max-w-full max-h-[90vh] object-contain"
        @error="handleImageError"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, nextTick, computed, watch } from 'vue'
import { chatService } from '../../api/chatService'
import { useChatStore } from '../../store/chatStore'

const chatStore = useChatStore()

// 从store获取状态
const messages = computed(() => chatStore.currentMessages)
const sessions = computed(() => chatStore.sessions)
const currentSessionId = computed(() => chatStore.currentSessionId)
const enableImageGeneration = computed(() => chatStore.getImageGeneration())

// 本地状态
const inputMessage = ref('')
const isLoading = ref(false)
const messagesContainer = ref<HTMLElement>()
const streamingMessageIds = ref<Set<string>>(new Set())
const currentStreamingController = ref<AbortController | null>(null)
const showSuggestions = ref(false) // 控制提示词按钮的显示/隐藏
const showSessionList = ref(false) // 控制会话列表的显示/隐藏

// 图片模态框状态
const showImageModal = ref(false)
const modalImageUrl = ref('')

const quickSuggestions = ref([
  'Create a photorealistic portrait of a person',
  'Generate a fantasy landscape with mountains and lakes',
  'Transform this image into anime style',
  'Enhance the quality and details of this photo'
])

// 初始化
onMounted(() => {
  // 初始化聊天store
  chatStore.initialize()
  
  // 等待下一个tick确保store初始化完成
  nextTick(() => {
    // 如果当前会话没有消息，添加欢迎消息
    if (messages.value.length === 0) {
      console.log('添加欢迎消息到当前会话')
      chatStore.addMessage('assistant', '您好！我是您的搜词助手，请告诉我您要搜索的热词关键字以及热词地区。')
    }
  })
  
  // 使用事件委托来处理动态生成的图片点击
  document.addEventListener('click', handleImageClick)
  
  // 点击外部关闭会话列表
  document.addEventListener('click', handleClickOutside)
})

// 清理事件监听器
onUnmounted(() => {
  document.removeEventListener('click', handleImageClick)
  document.removeEventListener('click', handleClickOutside)
})

// 监听消息变化，自动滚动到底部
watch(messages, () => {
  nextTick(() => {
    scrollToBottom()
  })
}, { deep: true })

const sendMessage = async () => {
  if (!inputMessage.value.trim() || isLoading.value) return

  const userMessage = inputMessage.value.trim()
  chatStore.addMessage('user', userMessage)
  inputMessage.value = ''
  
  isLoading.value = true

  // 创建一个流式消息
  const streamingMessage = chatStore.addMessage('assistant', '', 'sending')
  streamingMessageIds.value.add(streamingMessage.id)

  // 创建AbortController用于停止请求
  const abortController = new AbortController()
  currentStreamingController.value = abortController

  try {
    // 直接传递图片生成开关状态给聊天服务
    await chatService.sendMessage(userMessage, (chunk: string) => {
      console.log('收到流式数据块:', chunk)
      // 流式更新消息内容 - 获取当前消息内容
      const currentMessage = chatStore.currentMessages.find(m => m.id === streamingMessage.id)
      if (currentMessage) {
        console.log('当前消息内容:', currentMessage.content)
        console.log('更新后内容:', currentMessage.content + chunk)
        chatStore.updateMessage(streamingMessage.id, {
          content: currentMessage.content + chunk,
          status: 'sending'
        })
      } else {
        console.error('找不到流式消息:', streamingMessage.id)
      }
    }, abortController.signal, enableImageGeneration.value)
    
    // 流式输出完成，更新状态
    chatStore.updateMessage(streamingMessage.id, { status: 'completed' })
    streamingMessageIds.value.delete(streamingMessage.id)
  } catch (error: any) {
    // 检查是否是用户主动停止
    if (error.name === 'AbortError') {
      const currentMessage = chatStore.currentMessages.find(m => m.id === streamingMessage.id)
      if (currentMessage) {
        chatStore.updateMessage(streamingMessage.id, {
          content: currentMessage.content + '\n\n[Response stopped by user]',
          status: 'completed'
        })
      }
    } else {
      // 如果流式输出失败，更新最后一条消息为错误信息
      chatStore.updateMessage(streamingMessage.id, {
        content: 'Sorry, I encountered an error. Please try again later.',
        status: 'error'
      })
      console.error('Chat error:', error)
    }
    // 移除流式状态
    streamingMessageIds.value.delete(streamingMessage.id)
  } finally {
    isLoading.value = false
    currentStreamingController.value = null
  }
}

const sendQuickMessage = (suggestion: string) => {
  inputMessage.value = suggestion
  // 自动发送消息
  sendMessage()
}

const toggleSuggestions = () => {
  showSuggestions.value = !showSuggestions.value
}

const toggleImageGeneration = () => {
  console.log('Toggle clicked, current state:', enableImageGeneration.value)
  console.log('Current session:', chatStore.currentSession)
  console.log('Current session ID:', chatStore.currentSessionId)
  
  const newState = !enableImageGeneration.value
  console.log('Setting image generation to:', newState)
  
  chatStore.setImageGeneration(newState)
  
  console.log('After setting, current state:', enableImageGeneration.value)
  console.log('Current session after update:', chatStore.currentSession)
}

// 会话管理方法
const createNewChat = () => {
  chatStore.createNewSession()
  showSessionList.value = false
}

const switchToSession = (sessionId: string) => {
  chatStore.switchToSession(sessionId)
  showSessionList.value = false
}

const deleteSession = (sessionId: string) => {
  if (confirm('Are you sure you want to delete this chat session?')) {
    chatStore.deleteSession(sessionId)
  }
}

const toggleSessionList = () => {
  showSessionList.value = !showSessionList.value
}

const handleClickOutside = (event: Event) => {
  const target = event.target as HTMLElement
  if (!target.closest('.relative')) {
    showSessionList.value = false
  }
}

const formatDate = (date: Date) => {
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  const minutes = Math.floor(diff / 60000)
  const hours = Math.floor(diff / 3600000)
  const days = Math.floor(diff / 86400000)
  
  if (minutes < 1) return 'Just now'
  if (minutes < 60) return `${minutes}m ago`
  if (hours < 24) return `${hours}h ago`
  if (days < 7) return `${days}d ago`
  
  return date.toLocaleDateString()
}

const stopStreaming = () => {
  if (currentStreamingController.value) {
    currentStreamingController.value.abort()
    currentStreamingController.value = null
  }
}

const formatMessage = (content: string) => {
  console.log('Processing content in EmbeddedChat:', content) // 调试日志
  
  // 首先尝试解析JSON格式的回复（包含图片）
  try {
    // 检查是否包含image_url关键词
    if (content.includes('image_url')) {
      console.log('Content contains image_url, attempting to parse JSON')
      
      // 先清理内容，处理可能的换行问题
      let cleanedContent = content
        .replace(/\n/g, ' ') // 将换行符替换为空格
        .replace(/\s+/g, ' ') // 将多个空格合并为一个
        .trim()
      
      console.log('Cleaned content:', cleanedContent)
      
      // 尝试多种JSON匹配模式
      let jsonMatch = cleanedContent.match(/\{[^{}]*"image_url"[^{}]*\}/)
      
      // 如果第一种模式没匹配到，尝试更宽松的匹配
      if (!jsonMatch) {
        jsonMatch = cleanedContent.match(/\{[\s\S]*?"image_url"[\s\S]*?\}/)
      }
      
      // 如果还是没匹配到，尝试匹配整个JSON对象
      if (!jsonMatch) {
        jsonMatch = cleanedContent.match(/\{[\s\S]*\}/)
      }
      
      // 如果原始内容没匹配到，尝试在原始内容中匹配
      if (!jsonMatch) {
        jsonMatch = content.match(/\{[\s\S]*\}/)
      }
      
      // 如果还是没匹配到，尝试匹配包含中文前缀的JSON
      if (!jsonMatch) {
        // 匹配类似 "我来帮您生成一张图片!我已经为您生成了以下图片:\n{\n\"prompt\":\"七龙珠\",\n\"image_url\": \"https://...\"\n}" 的格式
        jsonMatch = content.match(/[\s\S]*?(\{[\s\S]*?"image_url"[\s\S]*?\})[\s\S]*?/)
        if (jsonMatch) {
          jsonMatch[0] = jsonMatch[1] // 只保留JSON部分
        }
      }
      
      // 如果还是没匹配到，尝试更宽松的匹配（处理跨行JSON）
      if (!jsonMatch) {
        // 匹配任何包含image_url的JSON对象，即使前面有中文文本
        const lines = content.split('\n')
        for (let i = 0; i < lines.length; i++) {
          if (lines[i].includes('{') && content.includes('image_url')) {
            // 找到包含{的行，从这一行开始匹配到包含}的行
            let jsonStart = i
            let jsonEnd = i
            for (let j = i; j < lines.length; j++) {
              if (lines[j].includes('}')) {
                jsonEnd = j
                break
              }
            }
            if (jsonEnd > jsonStart) {
              const jsonLines = lines.slice(jsonStart, jsonEnd + 1)
              const jsonStr = jsonLines.join('\n')
              if (jsonStr.includes('image_url')) {
                jsonMatch = [jsonStr]
                break
              }
            }
          }
        }
      }
      
      if (jsonMatch) {
        let jsonStr = jsonMatch[0]
        console.log('Found JSON match:', jsonStr) // 调试日志
        
        // 清理JSON字符串，处理换行和格式问题
        jsonStr = jsonStr
          .replace(/\n/g, ' ') // 移除换行
          .replace(/\s+/g, ' ') // 合并多个空格
          .replace(/"image_url"\s*:\s*"([^"]*?)\s*"/g, '"image_url":"$1"') // 修复image_url的换行问题
          .trim()
        
        console.log('Cleaned JSON string:', jsonStr)
        
        const jsonData = JSON.parse(jsonStr)
        console.log('Parsed JSON data:', jsonData) // 调试日志
        
        if (jsonData.image_url) {
          // 构建包含图片的HTML内容
          let htmlContent = ''
          
          // 如果有prompt，显示提示词
          if (jsonData.prompt) {
            htmlContent += `<div class="image-prompt mb-3">
              <div class="text-sm text-gray-600 mb-2 font-medium">Prompt:</div>
              <div class="bg-gray-50 p-3 rounded-lg text-sm">${jsonData.prompt}</div>
            </div>`
          }
          
          // 显示图片
          htmlContent += `<div class="generated-image mb-3">
            <div class="text-sm text-gray-600 mb-2 font-medium">Generated Image:</div>
            <div class="image-container">
              <img 
                src="${jsonData.image_url}" 
                alt="Generated Image" 
                class="max-w-full h-auto rounded-lg shadow-md hover:shadow-lg transition-shadow duration-300 cursor-pointer generated-image-click"
                data-image-url="${jsonData.image_url}"
                loading="lazy"
              />
            </div>
          </div>`
          
          // 不显示JSON数据，只显示图片
          return htmlContent
        }
      }
    }
  } catch (error) {
    console.log('JSON parsing failed:', error)
    console.log('Not a JSON format, proceeding with normal markdown processing')
  }
  
  // 如果不是JSON格式，进行正常的markdown渲染
  // 处理换行
  content = content.replace(/\n/g, '<br>')
  
  // 处理代码块 - 添加更好的溢出处理
  content = content.replace(/```([\s\S]*?)```/g, '<pre class="message-code-block"><code>$1</code></pre>')
  
  // 处理行内代码 - 添加更好的溢出处理
  content = content.replace(/`([^`]+)`/g, '<code class="message-inline-code">$1</code>')
  
  // 处理粗体
  content = content.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
  
  // 处理斜体
  content = content.replace(/\*(.*?)\*/g, '<em>$1</em>')
  
  // 处理链接 - 添加溢出处理
  content = content.replace(/(https?:\/\/[^\s]+)/g, '<a href="$1" target="_blank" rel="noopener noreferrer" class="message-link">$1</a>')
  
  // 处理列表
  content = content.replace(/^\* (.+)$/gm, '<li class="list-item">$1</li>')
  content = content.replace(/^- (.+)$/gm, '<li class="list-item">$1</li>')
  content = content.replace(/^(\d+)\. (.+)$/gm, '<li class="list-item numbered">$1. $2</li>')
  
  // 处理表情符号
  content = content.replace(/✨/g, '<span class="emoji">✨</span>')
  content = content.replace(/😊/g, '<span class="emoji">😊</span>')
  content = content.replace(/🎨/g, '<span class="emoji">🎨</span>')
  content = content.replace(/💡/g, '<span class="emoji">💡</span>')
  
  return content
}

const scrollToBottom = () => {
  nextTick(() => {
    if (messagesContainer.value) {
      messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight
    }
  })
}

const isMessageStreaming = (messageId: string): boolean => {
  return streamingMessageIds.value.has(messageId)
}

const formatTime = (timestamp: Date) => {
  const date = new Date(timestamp)
  return date.toLocaleTimeString('en-US', { 
    hour: '2-digit', 
    minute: '2-digit',
    hour12: true
  })
}

// 图片相关方法
const openImageModal = (imageUrl: string) => {
  modalImageUrl.value = imageUrl
  showImageModal.value = true
}

const closeImageModal = () => {
  showImageModal.value = false
  modalImageUrl.value = ''
}

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = ''
  img.alt = '图片加载失败'
}

// 处理动态生成的图片点击事件
const handleImageClick = (event: Event) => {
  const target = event.target as HTMLElement
  if (target.classList.contains('generated-image-click')) {
    const imageUrl = target.getAttribute('data-image-url')
    if (imageUrl) {
      openImageModal(imageUrl)
    }
  }
}
</script>

<style scoped>
.embedded-chat-container {
  @apply bg-white rounded-lg shadow-lg border border-gray-200;
  max-height: 100%;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-header {
  @apply p-4 border-b border-gray-200 bg-gray-50 rounded-t-lg;
}

.chat-messages {
  @apply flex-1 p-4 space-y-4 overflow-y-auto;
}

.message-item {
  @apply flex;
}

.message {
  @apply max-w-xs lg:max-w-md relative;
  transition: all 0.2s ease-in-out;
}

.message:hover {
  @apply transform scale-105;
}

/* AI消息气泡样式 */
.message--assistant {
  @apply bg-white border border-gray-200 shadow-sm;
  border-radius: 1rem 1rem 1rem 0.25rem;
}

.message--assistant:hover {
  @apply shadow-md;
}

/* 用户消息气泡样式 */
.message--user {
  @apply bg-gradient-to-br from-blue-500 to-blue-600 text-white shadow-sm;
  border-radius: 1rem 1rem 0.25rem 1rem;
}

.message--user:hover {
  @apply shadow-md;
}

/* 消息对齐样式 - 由CSS文件处理 */

.message-content {
  @apply flex items-start space-x-3;
}

.message--user .message-content {
  @apply flex-row-reverse space-x-reverse;
}

.message-text {
  @apply flex-1;
  word-wrap: break-word;
  overflow-wrap: break-word;
}

/* AI消息内容样式 */
.ai-message-content {
  @apply text-gray-800 leading-relaxed;
}

.message-content-formatted {
  @apply text-sm leading-relaxed;
}

/* 思考指示器样式 */
.thinking-indicator {
  @apply flex items-center space-x-3 text-gray-500;
}

.thinking-dots {
  @apply flex space-x-1;
}

.thinking-dots .dot {
  @apply w-2 h-2 bg-gray-400 rounded-full animate-bounce;
}

.thinking-dots .dot:nth-child(2) {
  animation-delay: 0.1s;
}

.thinking-dots .dot:nth-child(3) {
  animation-delay: 0.2s;
}

.thinking-text {
  @apply text-sm font-medium;
}

/* 用户消息内容样式 */
.user-message-content {
  @apply text-white leading-relaxed;
}

/* 消息内容格式化样式 */
.message-content-formatted strong {
  @apply font-semibold text-gray-900;
}

.message-content-formatted em {
  @apply italic text-gray-700;
}

.message-content-formatted code {
  @apply bg-gray-100 text-gray-800 px-1.5 py-0.5 rounded text-xs font-mono;
}

.message-content-formatted .code-block {
  @apply bg-gray-100 p-3 rounded-lg text-xs font-mono overflow-x-auto my-2;
}

.message-content-formatted .inline-code {
  @apply bg-gray-100 text-gray-800 px-1.5 py-0.5 rounded text-xs font-mono;
}

.message-content-formatted .message-link {
  @apply text-blue-600 hover:text-blue-800 underline transition-colors;
}

.message-content-formatted .list-item {
  @apply block py-1 pl-4 relative;
}

.message-content-formatted .list-item:before {
  content: "•";
  @apply absolute left-0 text-gray-500;
}

.message-content-formatted .list-item.numbered:before {
  content: counter(list-counter);
  counter-increment: list-counter;
}

.message-content-formatted .emoji {
  @apply text-lg;
}

/* 流式光标样式 */
.streaming-cursor {
  @apply inline-block text-blue-600 font-bold ml-1;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

/* 消息元信息样式 */
.message-meta {
  @apply flex items-center justify-between mt-2 pt-2 border-t border-gray-100;
}

.message-timestamp {
  @apply text-xs text-gray-500;
}

.message-status {
  @apply flex items-center space-x-1;
}

.status-dot {
  @apply w-2 h-2 bg-green-500 rounded-full animate-pulse;
}

.status-text {
  @apply text-xs text-green-600 font-medium;
}

.user-message-meta {
  @apply flex justify-end mt-2;
}

.user-message-timestamp {
  @apply text-xs text-blue-100;
}

.message-avatar {
  @apply flex-shrink-0;
}

.chat-input-container {
  @apply p-4 border-t border-gray-200 bg-gray-50 rounded-b-lg;
}

.prose {
  @apply text-sm;
  word-wrap: break-word;
  overflow-wrap: break-word;
  white-space: pre-wrap;
}

.prose strong {
  @apply font-semibold text-gray-900;
}

.prose em {
  @apply italic text-gray-700;
}

.streaming-cursor {
  @apply inline-block text-primary-600 font-bold;
  animation: blink 1s infinite;
}

@keyframes blink {
  0%, 50% { opacity: 1; }
  51%, 100% { opacity: 0; }
}

/* 空状态样式 */
.empty-state {
  @apply flex items-center justify-center h-full min-h-96;
}

.empty-state-content {
  @apply text-center max-w-md mx-auto px-6;
}

.empty-state-icon {
  @apply mb-4;
}

.empty-state-title {
  @apply text-xl font-semibold text-gray-900 mb-2;
}

.empty-state-description {
  @apply text-gray-600 mb-6 leading-relaxed;
}

.empty-state-actions {
  @apply flex justify-center;
}

.empty-state-button {
  @apply px-6 py-3 bg-primary-600 text-white rounded-lg hover:bg-primary-700 transition-colors duration-200 font-medium;
}
</style>
